package jeye.listeners.db;


import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jeye.dao.EventDAO;
import jeye.events.MotionDetectionEvent;
import jeye.listeners.MotionDetectionListener;
import jeye.utils.FileUtils;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

public class SaveEventFramesListener implements MotionDetectionListener {
	
	private static final Logger LOG = Logger.getLogger(SaveEventFramesListener.class);
	
	@Autowired
	private EventDAO eventDAO;

	public void onMotionDetection(MotionDetectionEvent motionDetectionEvent) {
		String eventUUID = motionDetectionEvent.getEventUUID();
		
		LOG.debug("Saving event frames into database...");
		
		eventDAO.saveMotionDetectionImages(motionDetectionEvent.getId(), getEventFramesMap(eventUUID));
		
		LOG.debug("Saving event frames into database... completed.");
	}
	
	private Map<Long, byte[]> getEventFramesMap(String eventUUID) {
		Map<Long, byte[]> result = new HashMap<Long, byte[]>();
		List<File> eventFrames = FileUtils.getEventFrames(eventUUID);
		
		for (File file : eventFrames) {
			String filename = file.getName();
			String timestampStr = filename.substring(0, filename.lastIndexOf("."));
			
			result.put(Long.parseLong(timestampStr), FileUtils.getBytesFromFile(file));
		}
		
		return result;
	}

}
